package cn.minhx.domain.trade.service.settlement.filter;

import cn.minhx.domain.trade.adapter.repostitory.ITradeRepository;
import cn.minhx.domain.trade.moedel.entity.MarketPayOrderEntity;
import cn.minhx.domain.trade.moedel.entity.TradeSettlementRuleCommandEntity;
import cn.minhx.domain.trade.moedel.entity.TradeSettlementRuleFilterBackEntity;
import cn.minhx.domain.trade.service.settlement.factor.TradeSettlementRuleFilterFactory;
import cn.minhx.types.design.link.multi.handler.ILogicHandler;
import cn.minhx.types.enums.ResponseCode;
import cn.minhx.types.exception.AppException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 外部交易单号过滤；外部交易单号是否为退单
 *
 * @author min
 */
@Slf4j
@Service
public class OutTradeNoRuleFilter
		implements
			ILogicHandler<TradeSettlementRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeSettlementRuleFilterBackEntity> {

	@Resource
	private ITradeRepository repository;

	@Override
	public TradeSettlementRuleFilterBackEntity apply(TradeSettlementRuleCommandEntity requestParameter,
			TradeSettlementRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
		log.info("结算规则过滤-外部单号校验{} outTradeNo:{}", requestParameter.getUserId(), requestParameter.getOutTradeNo());
		// 查询拼团信息
		MarketPayOrderEntity marketPayOrderEntity = repository
				.queryMarketPayOrderEntityByOutTradeNo(requestParameter.getUserId(), requestParameter.getOutTradeNo());

		if (null == marketPayOrderEntity) {
			log.error("不存在的外部交易单号或用户已退单，不需要做支付订单结算:{} outTradeNo:{}", requestParameter.getUserId(),
					requestParameter.getOutTradeNo());
			throw new AppException(ResponseCode.E0104);
		}
		dynamicContext.setMarketPayOrderEntity(marketPayOrderEntity);
		return next(requestParameter, dynamicContext);
	}
}
